import { Component } from '@angular/core';
import { NavParams, ViewController, ModalController, AlertController } from 'ionic-angular';
import { TaskDetailService } from './detail.service';
import { Common } from '../../../providers/common';
import {Storage} from '@ionic/storage';
import { Config } from '../../../providers/config';
import { ContactChoosePage } from '../../contact/choose/choose.component';
import { EmailDetailService } from '../../email/detail/detail.service';
import _ from 'lodash';
import {EmpPage} from "./emp.component";


@Component({
  selector: 'page-task-flowPress',
  templateUrl: './flowPress.html',
  providers: [TaskDetailService,EmailDetailService]
})
export class FlowPressPage {
	moa_page_name: any = "page-task-flowPress";
  moa_page_explain: any = "流程催办";

  // 催办群体,如：张三,李四,王五
  wkiUserName;
  // 催办群体ID 如：123,232,343
  wkiUserId;
  // 催办意见
  wkiDesc = "";
  // 当前登录人ID
  loginId;
  // 业务ID
  bid = "";
  // 催办标题
  wkiTitle = "";
  // 模版ID
  bomid = "";

  // 缓存通过组织树选择的人员
  // 结构如下：
  // [{
  //   empid:"A938493525",
  //   name:"冯镜蒯",
  //   orgid:"xtyfz",
  //   loginid:"fengjk",
  //   titleid:"ybyg"
  // },{}]
  defaultEmpByTree = [];

  // 是否选中 邮件催办
  isChecked = false;

  isSelectOne = null;
  isSelAddr = "";
  empnames = [];
  empnamesId = [];
  defaultEmpnames = [];
  defaultEmpnamesId = [];

  //通知方式，isToRead送阅，isEmail邮件，isSMS短信
  notifyType = {
    isToRead: true,
    isEmail: false,
    isSMS: false
  };

  isPressSuccess = true;//催办提交是否成功

  constructor(
    public navParams: NavParams,
    public viewCtrl: ViewController,
    public modalCtrl: ModalController,
    public alertCtrl: AlertController,
    public detailService: TaskDetailService,
    public emailDetailService: EmailDetailService,
    public common: Common,
    public storage: Storage
  ) {
    let that = this;
      this.storage.get("FlowPressPageParams").then(params => {
        this.loginId = params.loginId;//this.navParams.get('loginId');
        this.bid = params.bid;//this.navParams.get('bid');
        this.wkiTitle = params.wkiTitle;//this.navParams.get('wkiTitle');
        this.bomid = params.bomid;//this.navParams.get('bomid');
        console.log(this.bomid);

        this.isSelAddr = params.isSelAddr;//this.navParams.get("isSelAddr");
        this.empnames = params.empnames;//this.navParams.get("empnames");
        this.empnamesId = params.empnamesId;//this.navParams.get("empnamesId");
        this.defaultEmpnames = params.defaultEmpnames;//this.navParams.get("defaultEmpnames");
        this.defaultEmpnamesId = params.defaultEmpnamesId;//this.navParams.get("defaultEmpnamesId");

        this.wkiUserName = _.toString(this.defaultEmpnames);
        this.wkiUserId = this.defaultEmpnamesId;

        console.log(this.isSelAddr);
        console.log(this.empnames);
        console.log(this.empnamesId);
        console.log(this.defaultEmpnames);
        console.log(this.defaultEmpnamesId);

        that.storage.remove("FlowPressPageParams");
      });

  }

  complete() {
    this.dismiss({});
  }

  dismiss(data?: any) {
    // using the injected ViewController this page
    // can "dismiss" itself and pass back data
    this.viewCtrl.dismiss(data);
  }

  /**
   * [chooseUser 选择催办人]
   */
  chooseUser() {
    let that = this;

    // 有提供默认的选择人员时在默认人员肿选择，如果没有提供默人员则在组织树选择
    if (this.empnames.length > 0) {
      let modal = this.modalCtrl.create(EmpPage, {
        "isSelectOne": this.isSelectOne,
        "isSelAddr": this.isSelAddr,
        "empnames": this.empnames,
        "empnamesId": this.empnamesId,
        "defaultEmpnames": this.defaultEmpnames,
        "defaultEmpnamesId": this.defaultEmpnamesId
      });
      modal.present();

      modal.onWillDismiss((data: any) => {
        console.log(data);
        if (data) {
          that.defaultEmpnames = data.defaultEmpnames;
          that.defaultEmpnamesId = data.defaultEmpnamesId;
          that.wkiUserName = _.toString(data.defaultEmpnames);
          that.wkiUserId = data.defaultEmpnamesId;
        }
      });
    } else {
      let modal = this.modalCtrl.create(ContactChoosePage, {
        selected: this.defaultEmpByTree
      });

      modal.present();
      modal.onWillDismiss((data: any[]) => {
        //console.info("##催办人员：" + data);
        if (data) {
          that.defaultEmpByTree = data;
          that.wkiUserName = _.toString(_.map(data, "name"));
          that.wkiUserId = _.map(data, "loginid");//this.common.formatContactListData(data);
        }
      });

    }
  }

  /**
   * [checkConfirmData 催办数据提交校验]
   */
  checkConfirmData() {
    let retVal: any = {
      result: true, // 是否校验通过
      message: "您确认提交？" // 提示信息
    };

    if (this.bid == "" || this.wkiTitle == "" || this.bomid == "") {
      retVal.result = false;
      retVal.message = "数据有异常,提交失败！";
    } else if (this.wkiUserId.length < 1) {
      retVal.result = false;
      retVal.message = "催办对象不能为空！";
    }

    if (!this.notifyType.isToRead && !this.notifyType.isEmail && !this.notifyType.isSMS) {
      retVal.result = false;
      retVal.message = "请至少选择一种通知方式";
    }

    return retVal;
  }

  /**
   * [update 更新催办]
   */
  update() {
    var that = this;
    let params = {
      "loginId": "fengjk",
      "bid": this.bid,
      "wkiTitle": this.wkiTitle,
      "bomid": this.bomid,
      "wkiUser": _.toString(this.wkiUserId),
      "wkiDesc": this.wkiDesc
    };
    console.log("##催办提交：");
    console.log(params);
    if (this.notifyType.isToRead) {
      this.detailService.addPress(params).subscribe(data => {
        //console.log("## 催办返回信息");
        //console.log(data);
        if (data.msg == "成功！" && data.code == "0") {

        } else {
          this.isPressSuccess = false;
          let alert = this.alertCtrl.create({ // 有异常信息，弹出提示
            title: "异常信息提示",
            message: data.exception,
            buttons: [
              {
                text: "确定",
                role: 'cancel',
                handler: () => {
                  //console.log('Cancel clicked');
                }
              }
            ]
          });
          alert.present();
        }
      });
    }

    if (this.notifyType.isEmail) {
      this.sendEmail();
    }

    if (this.notifyType.isSMS) {
      this.sendSMS();
    }

    if (this.isPressSuccess) {
      let alert = that.alertCtrl.create({ // 有异常信息，弹出提示
        title: "提示",
        message: "催办提交成功！",
        buttons: [
          {
            text: "确定",
            handler: () => {
              this.dismiss();
            }
          }
        ]
      });
      alert.present();
    }
  }

  sendEmail() {
    // /Legion/Platform/FlowsComponent/BoFProIndex.jsp?bosid=900902&bomid=t_caipx_test
    let desc = "您OA系统中有一份 " + this.wkiTitle + " 文件催办事项！请登录OA系统办理！具体的催办意见为："
      + this.wkiDesc + "。";
    var sendBody = {
      bostitle: "（催办）" + this.wkiTitle,
      content: desc + '<a href="/Legion/Platform/FlowsComponent/BoFProIndex.jsp?bosid=' + this.bid + '&amp;bomid=t_caipx_test" data-ke-src="/Legion/Platform/FlowsComponent/BoFProIndex.jsp?bosid=' +  this.bid +'&amp;bomid=t_caipx_test" target="_blank">点击查看详细</a>',
      isreceipt: 0,
      login: "",
      otherlist: "",
      recievelist: this.wkiUserId,
      secretlist: "",
      urgency: 9
    };

    this.emailDetailService.sendEmail(sendBody).subscribe(data=>{
      console.log(data);
      if (data) {

      } else {
        this.isPressSuccess = false;
        let alert = this.alertCtrl.create({ // 有异常信息，弹出提示
          title: "异常信息提示",
          message: "催办邮件发送失败",
          buttons: [
            {
              text: "确定",
              role: 'cancel',
              handler: () => {
                //console.log('Cancel clicked');
              }
            }
          ]
        });
        alert.present();
      }
    });
  }

  sendSMS() {
    let content = "您OA系统中有一份 " + this.wkiTitle
      + " 文件催办事项！请登录OA系统处理！具体的催办意见为：" + this.wkiDesc;

    this.storage.get("contact-user-list").then(u => {
      _.forEach(this.wkiUserId, userid => {
        let temp = _.find(u, ["loginid", userid]);
        let params = {
          "mobile": temp["empmobile"],
          "content": content
        };

        this.detailService.sendSMS(params)
          .subscribe(result => {
            if (!result.isSuccess) {
              let alert = this.alertCtrl.create({ // 有异常信息，弹出提示
                title: "异常信息提示",
                message: "给 " + temp["emname"] + " 的手机短信发送失败",
                buttons: [
                  {
                    text: "确定",
                    role: 'cancel',
                    handler: () => {
                      //console.log('Cancel clicked');
                    }
                  }
                ]
              });
              alert.present();
            }
          });
      });
    });
  }

  /**
   * [confirm 提交催办]
   */
  confirm() {
    let checkResult = this.checkConfirmData();
    if (!checkResult.result) {
      let alert = this.alertCtrl.create({
        title: "提示",
        message: checkResult.message,
        buttons: [
          {
            text: "确定",
            role: 'cancel',
            handler: () => {
              //console.log('Cancel clicked');
            }
          }
        ]
      });
      alert.present();
    } else {
      let alert = this.alertCtrl.create({
        title: "提示",
        message: checkResult.message,
        buttons: [
          {
            text: '取消',
            role: 'cancel',
            handler: () => {
              //console.log('Cancel clicked');
            }
          },
          {
            text: "确定",
            handler: () => {
              this.update();
            }
          }
        ]
      });
      alert.present();
    }
  }

  // 各方式的勾选状态切换
  iocnCheck(type){
    switch (type) {
      case "isEmail":
        this.notifyType.isEmail = !this.notifyType.isEmail;
        break;
      case "isSMS":
        this.notifyType.isSMS = !this.notifyType.isSMS;
        break;
    }
  }

}
